package dao

import (
	"activity_srv/basic/config"
	__ "activity_srv/basic/proto"
	"activity_srv/handler/models"
	"encoding/json"
	"errors"
)

// 规则添加数据
var RuleData = models.DistributionRest{
	Pattern:                     "1",  //模式  1 指定分销 2 人人分销 3 满额分销
	Me:                          "2",  //自购不反
	PullPeopleReturnPrice:       "3",  //拉取人返回多少钱
	Member:                      "0",  //是否给用户发分销佣金  0不发 -1不限制
	OneRebate:                   "20", //一级返佣百分比
	TwoRebate:                   "30", //二级返佣百分比
	TPriceTime:                  "3",  //冻结时间 按天数
	EndPrice:                    "6",  //体现最低金额
	WithdrawType:                "1",  //提现方式  1支付宝  2 微信 3数字人名币 4银联
	WithdrawTypeProceduresPrice: "3",  //提现手续费
}

// AddDistribution 添加设置表
func AddDistributionRest(in *__.DistributionReq) (models.DistributionData, error) {
	//序列化规则结构体
	marshal, _ := json.Marshal(RuleData)
	var distribution models.DistributionData
	var err error
	distribution.DistributionType = uint64(in.DistributionType)
	distribution.Status = uint64(in.Status)
	distribution.DistributionRest = string(marshal)
	if err = distribution.AddDistribution(); err != nil {
		return distribution, errors.New("添加失败")
	}
	return distribution, nil
}

// 获取所有一级分销ID，存储到中间集合
func GetFirstLevelUserIds(userId int64) ([]int64, error) {
	var search models.DistributionSearch
	oneList, err := search.DistributionSearchList(userId)
	if err != nil {
		return nil, err
	}

	// 提取所有一级用户ID
	var userIds []int64
	for _, item := range oneList {
		userIds = append(userIds, int64(item.UserId))
	}
	return userIds, nil
}

// 批量获取二级分销数据通过所有一级用户ID
func GetSecondLevelData(firstLevelUserIds []int64) ([]models.DistributionSearch, error) {
	var allSecondLevel []models.DistributionSearch
	var search models.DistributionSearch

	// 循环一级用户ID，但内部不再嵌套业务逻辑
	for _, uid := range firstLevelUserIds {
		secondList, err := search.DistributionSearchList(uid)
		if err != nil {
			return nil, err // 可以根据实际需求决定是否忽略单个错误
		}
		allSecondLevel = append(allSecondLevel, secondList...)
	}
	return allSecondLevel, nil
}

// 转换数据格式
func convertToProtoFormat(secondLevelData []models.DistributionSearch) []*__.DistributionSearchList {
	var result []*__.DistributionSearchList
	for _, item := range secondLevelData {
		result = append(result, &__.DistributionSearchList{
			Id:          int64(item.Id),
			UserId:      int64(item.UserId),
			Nickname:    item.Nickname,
			FId:         int64(item.FId),
			Mobile:      item.Mobile,
			Price:       int64(item.Price),
			FreezePrice: int64(item.FreezePrice),
		})
	}
	return result
}

// OneDistributionSearchList 查询二级分销下下级
func OneDistributionSearchList(in *__.DistributionSearchListReq) ([]*__.DistributionSearchList, error) {
	// 步骤1：获取一级用户ID列表
	firstLevelIds, err := GetFirstLevelUserIds(in.UserId)
	if err != nil {
		return nil, errors.New("获取一级分销数据失败: " + err.Error())
	}

	// 步骤2：批量获取二级分销数据
	secondLevelData, err := GetSecondLevelData(firstLevelIds)
	if err != nil {
		return nil, errors.New("获取二级分销数据失败: " + err.Error())
	}

	// 步骤3：转换数据格式
	result := convertToProtoFormat(secondLevelData)

	if len(result) == 0 {
		return result, errors.New("未查询到数据")
	}
	return result, nil
}

// DistributionSearchListProcess 二级分销查询下下级列表 （查询过程）
func DistributionSearchListProcess(in *__.DistributionSearchListProcessReq) (models.DistributionSearch, error) {
	var distribution models.DistributionSearch
	distribution.UserId = uint64(in.UserId)
	if err := distribution.GetDistributionUserId(); err != nil {
	}
	return distribution, nil
}

// OneListTwoListDistributionSearchListProcess 二级分销一级查询
func OneListTwoListDistributionSearchListProcess(userId int64) []*__.OneDistributionSearchListProcess {
	var distribution models.DistributionSearch
	list, _ := distribution.DistributionSearchList(userId)
	var oneList []*__.OneDistributionSearchListProcess
	for _, item := range list {
		oneList = append(oneList, &__.OneDistributionSearchListProcess{
			Id:          int64(item.Id),
			UserId:      int64(item.UserId),
			Nickname:    item.Nickname,
			FId:         int64(item.FId),
			Mobile:      item.Mobile,
			Price:       int64(item.Price),
			FreezePrice: int64(item.FreezePrice),
			SumPrice:    int64(item.SumPrice),
			TwoList:     TwoListDistributionSearchListProcess(int64(item.UserId)),
		})
	}
	return oneList
}

// TwoListDistributionSearchListProcess  二级分销第二级查询
func TwoListDistributionSearchListProcess(userId int64) []*__.TwoDistributionSearchListProcess {
	var distribution models.DistributionSearch
	list, _ := distribution.DistributionSearchList(userId)
	var twoList []*__.TwoDistributionSearchListProcess
	for _, item := range list {
		twoList = append(twoList, &__.TwoDistributionSearchListProcess{
			Id:          int64(item.Id),
			UserId:      int64(item.UserId),
			Nickname:    item.Nickname,
			FId:         int64(item.FId),
			Mobile:      item.Mobile,
			Price:       int64(item.Price),
			FreezePrice: int64(item.FreezePrice),
			SumPrice:    int64(item.SumPrice),
		})
	}
	return twoList
}

// AddDistributionPoster 添加二级分销海报
func AddDistributionPoster(in *__.DistributionPosterReq) (models.DistributionData, error) {
	var distribution models.DistributionData
	var err error
	distribution.Id = uint32(in.Id)
	if err = distribution.GetDistributionId(); err != nil {
		return distribution, errors.New("查询失败")
	}
	poster := config.POSTER_IMG_URL
	distribution.Poster = poster
	if err = distribution.AddPoster(); err != nil {
		return distribution, errors.New("添加失败")
	}
	return distribution, err
}

// 二级分销排行榜
func DistributionSortList(in *__.DistributionSortListReq) []*__.DistributionSortList {
	var Distribution models.DistributionSearch
	list, _ := Distribution.DistributionSort(in.ListType, in.Limit)
	var List []*__.DistributionSortList
	for _, item := range list {
		List = append(List, &__.DistributionSortList{
			Id:          uint64(item.Id),
			UserId:      int64(item.UserId),
			Nickname:    item.Nickname,
			FId:         item.FId,
			Mobile:      item.Mobile,
			Price:       float32(item.Price),
			FreezePrice: float32(item.FreezePrice),
			PullPeople:  item.PullProple,
		})
	}
	return List
}
